package util

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const RemoteUlr = "https://oapi.dingtalk.com/robot/send?access_token=7d517a7780c830b7007464759910cc5643bdcfb682e30232f6f9260ba9b0bc0f"

type AlarmMessage struct {
	MessageType string `json:"msgtype"`
	MarkDown    struct {
		Title string `json:"title"`
		Text  string `json:"text"`
	} `json:"markdown"`
}

func SendAlarm(title, text string) error {
	alarmmessage := new(AlarmMessage)
	alarmmessage.MessageType = "markdown"
	alarmmessage.MarkDown.Text = text
	alarmmessage.MarkDown.Title = fmt.Sprintf("#%s\n > %s", title, text)

	if bts, err := json.Marshal(alarmmessage); err == nil {
		res, err := http.Post(RemoteUlr, "application/json;charset=utf-8", bytes.NewBuffer(bts))
		if err == nil {
			defer res.Body.Close()
			_, err := ioutil.ReadAll(res.Body)
			return err
		}
		return err
	} else {
		return err
	}

}
